package com.ericsson.enap.modules.backup.task;

import com.alibaba.fastjson.JSON;
import com.ericsson.common.pojo.FTPInfoVO;
import com.ericsson.common.quartz.task.ManualTask;
import com.ericsson.common.util.DateUtils;
import com.ericsson.common.util.FileUtil;
import com.ericsson.common.util.SFtpCarrierUtilNew;
import com.ericsson.enap.modules.backup.entity.SysLogininfor;
import com.ericsson.enap.modules.backup.entity.SysOperLog;
import com.ericsson.enap.modules.backup.service.ImsLogBackupService;
import com.jcraft.enipjsch.Channel;
import com.jcraft.enipjsch.ChannelExec;
import com.jcraft.enipjsch.ChannelSftp;
import com.jcraft.enipjsch.JSch;
import com.jcraft.enipjsch.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * @description: 湖北登录日志，话单日志备份Task
 * @author: chenhongbo
 * @create: 2021-10-19 09:47
 */

@Component
public class ImsLogBackupTask implements ManualTask {

    @Autowired
    private ImsLogBackupService imsLogBackupService;




    @Override
    public void execute() {
        String path = "/opt/Ericsson/core/syslog";
        //String path = "D:/";
        String beforeDate = DateUtils.beforNumDay(new Date(),-2);
        //String beforeDate = "2021-11-19";
        List<SysLogininfor>  loginList = imsLogBackupService.querySysLogininforList(beforeDate + " 00:00:00", beforeDate + " 23:59:59");
        List<SysOperLog>  operList = imsLogBackupService.querySysOperLogList(beforeDate + " 00:00:00", beforeDate + " 23:59:59");
        try {
            if(loginList.size() > 0) {
                File loginFile = new File(path + File.separator + "login"+beforeDate+ ".log");
                loginFile.createNewFile();
                this.writeToFile(toObject(loginList), loginFile);
                this.upLoad(loginFile);
            }
            if(operList.size() > 0) {
                File operFile = new File(path + File.separator + "oper"+beforeDate+ ".log");
                operFile.createNewFile();
                this.writeToFile(toObject(operList), operFile);
                this.upLoad(operFile);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private <E> List<Object> toObject(List<E> list){
        List<Object> objlist = new ArrayList<Object>();
        for(Object e : list){
            String log = "";
            if(e instanceof SysLogininfor) {
                SysLogininfor login = (SysLogininfor)e;
                log = login.getUserName() + "," + login.getIpaddr() + "," + login.getLoginLocation() + "," + login.getOs() + "," + login.getMsg() + "," + DateUtils.formatDate(login.getLoginTime(),"yyyy-MM-dd HH:mm:ss");
            } else {
                SysOperLog operLog = (SysOperLog)e;
                log = operLog.getTitle() + "," + operLog.getOperName() + "," + operLog.getOperIp() + "," + operLog.getOperLocation() + "," + operLog.getOperParam() + "," + DateUtils.formatDate(operLog.getOperTime(),"yyyy-MM-dd HH:mm:ss");
            }
            Object obj = (Object)log;
            objlist.add(obj);

        }
        return objlist;
    }


    /*public void writeToFile(List<Object> list, File file) {

        try {
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            for (int i = 0; i < list.size(); i++) {
                bw.write(list.get(i)+"\r\n");
            }
            fw.flush();
            bw.flush();
            bw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }*/


    public void writeToFile(List<Object> content, File file) {
        FileWriter fw = null;
        PrintWriter pw = null;
        try {
            if (file.exists()) {
                fw = new FileWriter(file);
                pw = new PrintWriter(fw);
                for(Object o : content) {
                    pw.println(o + "\r\n");
                }
                pw.flush();
                fw.flush();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            pw.close();
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

   /* private void downLoad() {
        FTPInfoVO ftpInfo = new FTPInfoVO();
        ftpInfo.setHost("net.getIp4()");
        ftpInfo.setUserName("net.getUsername()");
        ftpInfo.setPassword("net.getPassword()");
        ftpInfo.setPath("ftpPath");
        ftpInfo.setPort(21);
        System.out.println("--------------------- ftpInfo:" + ftpInfo);
        SFtpCarrierUtilNew sftpCarrier = new SFtpCarrierUtilNew(ftpInfo, log);
        sftpCarrier.downloadFile(ftpInfo.getPath(), filename, filePath +"/"+bizName+"/", filename);
    }*/

    private void upLoad(File f) {

        String username = "mingan1";
        String ip = "10.25.114.85";
        String password = "Lahmy1c!";
        String workingDir = "/opt/ftpfile2/hxw/IMS/";
        Session session = null;
        ChannelSftp channelSftp = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, ip, 22);
            session = jsch.getSession(username, ip, 22);
            session.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("kex","diffie-hellman-group1-sha1");
            sshConfig.put("StrictHostKeyChecking", "no");
            session.setConfig(sshConfig);
            session.connect();
            Channel channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            channelSftp.cd(workingDir);
            channelSftp.put(new FileInputStream(f), f.getName());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channelSftp != null && !channelSftp.isClosed()) {
                channelSftp.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }

    }
}
